# -*- coding: utf8 -*-

import os
import hashlib

# Ouput csv format:
# name,sex,age,contact,address,unit,other,hospital,section,status,hospital_contact,source,shard,pid
FIELDS = ("name", "sex", "age", "contact", "address", "unit", "other",
          "hospital", "section", "status", "hospital_contact", "source")

FIELDS_ZH = ["姓名", "性别", "年龄", "联系电话", "家庭住址", "单位/学校",
             "其他", "医院", "科室", "伤情", "医院联系方式", "来源", "shard", "pid"]

def Writer(outfname, persons, starting_shard, shard_size):
    basefname = os.path.basename(outfname)
    out = file(outfname, 'wb')
   
    # write header
    out.write(",".join(FIELDS_ZH));
    out.write("\n")

    for id, person in zip(xrange(len(persons)), persons):
       shard = starting_shard + (id / shard_size)
       shard_id = "%s-%05d" % (basefname, shard) 
       # hash of object
       pid =  hashlib.sha1(str(person)).hexdigest()
       for field in FIELDS:
         if person.__dict__[field]:
           out.write("%s," % person.__dict__[field])
         else:
           out.write(",")
       out.write("%s,%s\n" % (shard_id, pid))
    out.close()
